'use strict';

angular.module('memoriesApp')
.controller('PhotoListCtrl', function($scope, $rootScope, $log, $timeout, global, photoService, dataStoreFactory) {

  var photoStore = dataStoreFactory.get('photo');
  var events = global.events;
  var vm, cameraReady = true;

  function takePhoto() {
    if (cameraReady) {
      cameraReady = false;
      photoService.takePhoto(function(err, photoData) {
        if (!err) {
          photoStore.add({'uri': photoData}, function() {
            $timeout(updatePhotoList)
          });
        } else {
          $log.error('Take photo error! ' + photoData);
        }
        cameraReady = true;
      });
    }
  }

  function updatePhotoList() {
    photoStore.getList(function(err, list) {
      if (err) return;
      if (list && list.length) {
        $scope.vm.listEmpty = false;
      } else {
        $scope.vm.listEmpty = true;
      }
      if (list && list.length) {
        buildPhotoList(list);
      }
      $log.log('get photo list: ' + angular.toJson(list));
    });
  }

  function buildPhotoList(list) {
    var cols = 3, resultList = [], counter = 0, row, temp, flag = true;
    while(flag) {
      row = list.slice(counter, counter+cols);
      counter = counter + cols;
      if (row.length <= 0 || row.length < cols) {
        flag = false;
      }
      // fill row with empty object
      if (row.length > 0 && row.length < cols) {
        temp = row.length;
        while(temp < cols) {
          row.push({});
          temp++;
        }
      }
      resultList.push(row);
    }
    $scope.vm.photoList = resultList;
    $scope.$broadcast('scroll.refreshComplete');
  }

  function init() {
    $scope.vm = {};
    vm = $scope.vm;

    // right buttons on nav bar
    vm.rightButtons = [{
      type: 'button-positive',
      content: '<i class="icon ion-camera"></i>',
      tap: function(e) {
        takePhoto();
      }
    }];

    $rootScope.$on(events.updatePhoto, function(e) {
      updatePhotoList();
    });
    updatePhotoList();
  }

  init();

});